from django import forms
from django.http import JsonResponse
from django.shortcuts import render, redirect
from django.urls import reverse

from utils.bootstrap import BootstrapForm
from utils.pager import Pagination
from utils.response import BaseResponse
from web.models import PricePolicy


def policy_list(request):
    queryset = PricePolicy.objects.all()
    pager = Pagination(request, queryset)
    return render(request, 'policy_list.html', {'pager': pager})


class PolicyModelForm(BootstrapForm, forms.ModelForm):
    class Meta:
        model = PricePolicy
        fields = '__all__'


def policy_add(request):
    if request.method == 'GET':
        form = PolicyModelForm()
        return render(request, 'form2.html', {'form': form})

    form = PolicyModelForm(request.POST)
    if not form.is_valid():
        return render(request, 'form2.html', {'form': form})

    form.save()
    return redirect(reverse('policy_list'))


def policy_edit(request, pk):
    instance = PricePolicy.objects.filter(id=pk).first()
    if request.method == 'GET':
        form = PolicyModelForm(instance=instance)
        return render(request, 'form2.html', {'form': form})

    form = PolicyModelForm(data=request.POST, instance=instance)
    if not form.is_valid():
        return render(request, 'form2.html', {'form': form})

    form.save()
    return redirect(reverse('policy_list'))


def policy_delete(request):
    cid = request.GET.get('cid', 0)
    res = BaseResponse()

    if not cid:
        res.status = False
        res.detail = '请选择要删除的数据'
        return JsonResponse(res.dict)

    if not PricePolicy.objects.filter(id=cid).exists():
        res.status = False
        res.detail = '要删除的数据不存在'
        return JsonResponse(res.dict)

    PricePolicy.objects.filter(id=cid).delete()
    res.status = True
    return JsonResponse(res.dict)
